package com.bocai.dahuatech.ui.activity;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.bocai.dahuatech.Bean.BaseBean;
import com.bocai.dahuatech.Bean.ProductDetailBean;
import com.bocai.dahuatech.Bean.ProductFittingsBean;
import com.bocai.dahuatech.Bean.ProductParamBean;
import com.bocai.dahuatech.Bean.ProductTagBean;
import com.bocai.dahuatech.R;
import com.bocai.dahuatech.base.BaseActivity;
import com.bocai.dahuatech.event.MainEvent;
import com.bocai.dahuatech.ui.adapter.FlowAdapter;
import com.bocai.dahuatech.ui.frag.ProductParamFragment;
import com.bocai.dahuatech.ui.frag.ProductSizePicFragment;
import com.bocai.dahuatech.ui.view.MyListView;
import com.bocai.dahuatech.utils.AESUtils;
import com.bocai.dahuatech.utils.DialogUtil;
import com.bocai.dahuatech.utils.KeyBoardUtils;
import com.bocai.dahuatech.utils.LoginDialogUtil;
import com.bocai.dahuatech.utils.RZUtil;
import com.bocai.dahuatech.utils.SharePrefencesUtil;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import de.greenrobot.event.EventBus;
import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

public class NewProductDetailActivity extends BaseActivity implements View.OnClickListener{
    @Bind(R.id.productdetail_tab)
    TabLayout mTabLayout;
    @Bind(R.id.productdetail_vp)
    ViewPager viewPager;
    @Bind(R.id.tv_productdetail_addshoppingcard)
    TextView tvAddShoppingcard;
    @Bind(R.id.tv_productdetail_model)
    TextView tvModel;
    @Bind(R.id.tv_productdetail_name)
    TextView tvName;
    @Bind(R.id.tv_productdetail_price)
    TextView tvPrice;
    @Bind(R.id.tv_productdetail_visible_distributor)
    TextView tvDistribute;
    @Bind(R.id.iv_productdetail_pic)
    ImageView ivPic;
    private ImageView ivDismissPop;
    PopupWindow mHeadPopWindow;
    FlowAdapter adapter;
    int productId;
    String solutionId="0";
    ProductDetailBean productDetailBean;
    ProductFittingsBean productFittingsBean;
    int productTotalCount=1;
    private SharedPreferences preferences;
    ProductParamBean productParamBean;
    int what;
    @Override
    protected int contentView()
    {
        return R.layout.activity_product_detail;

    }

    @Override
    protected void initView()
    {
        ButterKnife.bind(this);
        initToolbar(R.string.productdetail);
        setSupportActionBar(mToolbar);
        productId=getIntent().getIntExtra("productId", -1);
        solutionId=getIntent().getStringExtra("solutionId");
        what=getIntent().getIntExtra("what",0);
        getProductDetail();
        initEvent();
    }

    private void isShowDialog() {
        preferences = getSharedPreferences("user",MODE_APPEND);
        int count = preferences.getInt("first", 0);
        if(count==0)
        {
            if(SharePrefencesUtil.getFAccessFlag(this)==7)
            {

                DialogUtil.dialogForTwoButton(this, R.string.nodistributornotseeprice, R.string.know, R.string.toauthentication, new View.OnClickListener()
                {
                    @Override
                    public void onClick(View v)
                    {
                        RZUtil.renZheng(NewProductDetailActivity.this);
//                        Intent intent1=new Intent(ProductDetailActivity.this,RegistDistributorSecendActivity.class);
//                        IndividualBean bean=new IndividualBean();
//                        intent1.putExtra("register",bean);
//                        intent1.putExtra("what","certifiled");
//                        startActivity(intent1);
                        DialogUtil.dismissTowDialog();
                    }
                });
                SharedPreferences.Editor editor = preferences.edit();
                //存入数据
                editor.putInt("first", ++count);
                //提交修改
                editor.commit();

            }else  if(SharePrefencesUtil.getFAccessFlag(this)==0)
            {

                DialogUtil.dialogForTwoButton(this, R.string.nologinnotseeprice, R.string.know, R.string.tologin, new View.OnClickListener()
                {
                    @Override
                    public void onClick(View v)
                    {
                        Intent intent1=new Intent(NewProductDetailActivity.this, LoginActivity.class);
                        intent1.putExtra("tologin", false);
                        startActivity(intent1);
                        DialogUtil.dismissTowDialog();
                    }
                });
                SharedPreferences.Editor editor = preferences.edit();
                //存入数据
                editor.putInt("first", ++count);
                //提交修改
                editor.commit();

            }

        }

    }


    @Override
    protected void initEvent()
    {
        super.initEvent();
        tvDistribute.setOnClickListener(this);
        mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_collection, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch(item.getItemId()){
            case R.id.action_toshopcard:
                //回到购物车
                if(what==0){

                    EventBus.getDefault().post(new MainEvent("goshopcart"));
                }else{
                    Intent intent=new Intent(this,HomeActivity.class);
                    intent.putExtra("what",1);
                    startActivity(intent);
                    EventBus.getDefault().post(new MainEvent("goshopcart"));
                }
                finish();
                break;
            case R.id.action_collection:
                //收藏
                if(SharePrefencesUtil.getFAccessFlag(NewProductDetailActivity.this)==0)
                {
                    LoginDialogUtil.loginDialog(NewProductDetailActivity.this);

                }else
                {
                    ifCollected();
                }
                break;
        }
        return true;
    }

    /**
     * 判断是否收藏
     */
    private void ifCollected()
    {
        getTestApi().ifNewsCollection(productId+"", 3, SharePrefencesUtil.getFID(this))
                .compose(this.<BaseBean>bindToLifecycle())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(ifCollectedObserver);
    }

    Observer<BaseBean> ifCollectedObserver=new Observer<BaseBean>()
    {
        @Override
        public void onCompleted()
        {

        }

        @Override
        public void onError(Throwable e)
        {
            Log.e("error", e.toString());
            hideLoading();
            showToast(R.string.neterror);
        }

        @Override
        public void onNext(BaseBean baseBean)
        {
            if(baseBean.getReturnInfo().equals(getResources().getText(R.string.nocollection)))
            {

                addCollection();
            }else
            {
                showToast(R.string.productalreadycollection);
            }
        }
    };


    /**
     * 添加收藏
     */
    private void addCollection()
    {
        getTestApi().addCollection(productId + "", "", 3, SharePrefencesUtil.getFID(this))
                .compose(this.<BaseBean>bindToLifecycle())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(addCollectionObserver);
    }
    Observer<BaseBean> addCollectionObserver=new Observer<BaseBean>()
    {
        @Override
        public void onCompleted()
        {

        }

        @Override
        public void onError(Throwable e)
        {
            hideLoading();
            showToast(R.string.neterror);
            Log.e("error",e.toString());

        }

        @Override
        public void onNext(BaseBean baseBean)
        {
            Log.e("info",baseBean.getReturnInfo());
            showToast(baseBean.getReturnInfo());
        }
    };
    /**
     * 获取产品详情数据
     */
    private void
    getProductDetail()
    {
        showLoading();
        getTestApi().getProductDetail(productId)
                .compose(this.<BaseBean>bindToLifecycle())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(productDetailObserver);
    }
    Observer<BaseBean> productDetailObserver=new Observer<BaseBean>()
    {
        @Override
        public void onCompleted()
        {

        }

        @Override
        public void onError(Throwable e)
        {
            hideLoading();
//            showToast("网络错误");
            Log.e("error", e.toString());
        }

        @Override
        public void onNext(BaseBean baseBean)
        {
            hideLoading();
            if(baseBean.getReturnNo().equals("1"))
            {
                String result= AESUtils.decode(baseBean.getContent());
                result=start+result+end;
                Log.e("result", result);
                productDetailBean=new Gson().fromJson(result,ProductDetailBean.class);
                setDatas();
                getProductParam();
                tvAddShoppingcard.setOnClickListener(NewProductDetailActivity.this);
            }else
            {
                showToast(baseBean.getReturnInfo());
            }
        }
    };

    /**
     * 获取产品参数详情
     */
    private void getProductParam()
    {
        getTestApi().getProductParamDetail(productId)
                .compose(this.<BaseBean>bindToLifecycle())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(productparamObserver);
    }

    Observer<BaseBean> productparamObserver=new Observer<BaseBean>()
    {
        @Override
        public void onCompleted()
        {
            isShowDialog();
        }

        @Override
        public void onError(Throwable e)
        {
            hideLoading();
            showToast(R.string.neterror);
        }

        @Override
        public void onNext(BaseBean baseBean)
        {
            if(baseBean.getReturnNo().equals("1"))
            {
                String result=AESUtils.decode(baseBean.getContent());
                result=start+result+end;
                Log.e("result",result);
                productParamBean=new Gson().fromJson(result,ProductParamBean.class);
                viewPager.setAdapter(new Adapter(getSupportFragmentManager()));
                mTabLayout.setupWithViewPager(viewPager);
                viewPager.setOffscreenPageLimit(2);
                mTabLayout.setTabMode(TabLayout.MODE_FIXED);
            }else
            {
                showToast(baseBean.getReturnInfo());
            }
        }
    };

    /**
     *设置数据
     */
    private void setDatas()
    {
        tvModel.setText(productDetailBean.getContent().getFOutModel());
        tvName.setText(productDetailBean.getContent().getFItemName());
        if(SharePrefencesUtil.getFAccessFlag(this)==2)
        {

            tvPrice.setText(getResources().getString(R.string.money) + productDetailBean.getContent().getFStandPrice());
//            tvDistribute.setVisibility(View.GONE);
        }else
        {
//            tvPrice.setText("￥???");
            tvPrice.setText("");
//            tvDistribute.setVisibility(View.VISIBLE);
        }

        Glide.with(this).load(productDetailBean.getContent().getFPicPath())
                .into(ivPic);
    }



    @Override
    public void onClick(View v) {
        switch (v.getId())
        {
            case R.id.tv_productdetail_addshoppingcard:
                if(SharePrefencesUtil.getFAccessFlag(this)==0)//游客 去登录
                {
                    {
                        DialogUtil.dialogForTwoButton(this, R.string.nologin, R.string.know, R.string.tologin, new View.OnClickListener()
                        {
                            @Override
                            public void onClick(View v)
                            {
                                Intent intent=new Intent(NewProductDetailActivity.this, LoginActivity.class);
                                intent.putExtra("tologin",false);
                                startActivity(intent);
                                DialogUtil.dismissTowDialog();
                            }
                        });
                    }
                }
                else if(SharePrefencesUtil.getFAccessFlag(this)!=2) //个人  去认证
                {

                    DialogUtil.dialogForTwoButton(this, R.string.notaddshoppingcard, R.string.know, R.string.toauthentication, new View.OnClickListener()
                    {
                        @Override
                        public void onClick(View v)
                        {
                            if(SharePrefencesUtil.getFAccessFlag(NewProductDetailActivity.this)==6)
                            {
                                DialogUtil.dismissTowDialog();
                                DialogUtil.dialogForOneButton(NewProductDetailActivity.this,R.string.alreadysubmitdata,R.string.know);
                            }else  if(SharePrefencesUtil.getFAccessFlag(NewProductDetailActivity.this)==7)
                            {
                                RZUtil.renZheng(NewProductDetailActivity.this);
                                DialogUtil.dismissTowDialog();
                            }
                        }
                    });
                }else{
                    showPopwindow();
                }
                break;
            case R.id.iv_dismiss_pop:
                mHeadPopWindow.dismiss();
                break;
            //个人会员登录的话，点击分销商认证；游客登录的话，点击去登录
            case R.id.tv_productdetail_visible_distributor:
                if(SharePrefencesUtil.getFAccessFlag(this)==0)
                {
                    DialogUtil.dialogForTwoButton(this, R.string.nologin, R.string.know, R.string.tologin, new View.OnClickListener()
                    {
                        @Override
                        public void onClick(View v)
                        {
                            Intent intent=new Intent(NewProductDetailActivity.this, LoginActivity.class);
                            intent.putExtra("tologin", false);
                            startActivity(intent);
                            DialogUtil.dismissTowDialog();
                        }
                    });
                }else
                {

                    DialogUtil.dialogForTwoButton(this, R.string.nodistributornotseeprice, R.string.know, R.string.toauthentication, new View.OnClickListener()
                    {
                        @Override
                        public void onClick(View v)
                        {
                            if(SharePrefencesUtil.getFAccessFlag(NewProductDetailActivity.this)==6)
                            {
                                DialogUtil.dismissTowDialog();
                                DialogUtil.dialogForOneButton(NewProductDetailActivity.this,R.string.alreadysubmitdata,R.string.know);
                            }else  if(SharePrefencesUtil.getFAccessFlag(NewProductDetailActivity.this)==7)
                            {
                                RZUtil.renZheng(NewProductDetailActivity.this);
//                                Intent intent1=new Intent(ProductDetailActivity.this,RegistDistributorSecendActivity.class);
//                                IndividualBean bean=new IndividualBean();
//                                intent1.putExtra("register",bean);
//                                intent1.putExtra("what", "certifiled");
//                                startActivity(intent1);
                                DialogUtil.dismissTowDialog();
                            }
                        }
                    });
                }
                break;

            //产品数量增加
            case R.id.tv_pop_productdetail_add:
                productTotalCount=Integer.parseInt(tvPopNum.getText().toString());
                productTotalCount++;
                tvPopNum.setText(productTotalCount+"");
                break;
            //产品数量减少
            case R.id.tv_pop_productdetail_down:
                //添加
                int count=0;
                //循环计算所有已选配件的总数量
                for(int i=0;i<fitTotalCount.size();i++)
                {
                    if(fitChoose.get(i)){
                        count+=fitTotalCount.get(i);
                    }
                }
                productTotalCount=Integer.parseInt(tvPopNum.getText().toString());
                if(productTotalCount<=1||count>=productTotalCount)
                {
                    showToast(R.string.notless);
                }else{
                    productTotalCount--;
                    tvPopNum.setText(productTotalCount+"");
                }
                break;

            case R.id.tv_pop_productdetail_commit:
                //加入购物车
                int fitcount=0;
                //循环计算所有已选配件的总数量
                for(int i=0;i<fitTotalCount.size();i++)
                {
                    if(fitChoose.get(i))
                    {
                        fitcount+=fitTotalCount.get(i);
                    }
                }
                if(fitcount>productTotalCount)
                {
                    showToast("配件数量不能大于产品数量");
                }else{


                    StringBuffer sbCommitFits=new StringBuffer();
                    Log.e("productTotalCount",productTotalCount+"");
                    for(int i=0;i<productFittingsBean.getContent().size();i++)
                    {
                        Log.e("fitTotalCount  "+i  ,fitTotalCount.get(i)+"");
                        Log.e("fitChoose   "+i,fitChoose.get(i)+"");
                        if (fitChoose.get(i))
                        {
//                   int fitId= productFittingsBean.getContent().get(i).getFID();
                            if(fitTotalCount.get(i)!=0){
                                sbCommitFits.append(productFittingsBean.getContent().get(i).getFID()+"_"+fitTotalCount.get(i)+"_"+solutionId+"_0_"+productDetailBean.getContent().getFItemNumber());
                                sbCommitFits.append("|");
                            }
                        }
                    }
                    //产品ID主键_数量_解决方案ID_0：5_2_0_0
                    //配件的产品主键_数量_解决方案ID_0_父产品的FItemnumber | 配件的产品主键_数量_解决方案ID_0_父产品的FItemnumber：6_2_0_0_产品料号测试1@543731
                    String sb="";
                    if(sbCommitFits.length()!=0)
                    {
                        sb=sbCommitFits.substring(0,sbCommitFits.length()-1);
                    }
                    if(productTagBean!=null&&productTagBean.getContent()!=null&&productTagBean.getContent().size()==0)
                    {
                        //产品规格为空
                        showLoading();
                        getTestApi().addToCard(2,SharePrefencesUtil.getCustomerCode(this),SharePrefencesUtil.getFID(this),
                                solutionId,productId+"_"+productTotalCount+"_"+solutionId+"_0",sb).compose(this.<BaseBean>bindToLifecycle())
                                .subscribeOn(Schedulers.io())
                                .observeOn(AndroidSchedulers.mainThread())
                                .subscribe(commitObserver);
                    }else
                    {
                        //产品规格不为空
                        boolean ischoose=false;
                        for (int i=0;i<tagChoose.size();i++)
                        {
                            if(tagChoose.get(i)&&tagTotalCount.get(i)!=0){
                                ischoose=true;
                            }
                        }
                        if(!ischoose)
                        {
                            showToast("请选择购买产品规格及数量");
                        }
                        else
                        {
                            StringBuffer sbCommittags=new StringBuffer();
                            for (int i=0;i<tagChoose.size();i++)
                            {
                                if(tagChoose.get(i)){
                                    if(tagTotalCount.get(i)!=0)
                                    {
                                        sbCommittags.append(productTagBean.getContent().get(i).getFID()+"_"+tagTotalCount.get(i)+"_"+solutionId+"_0");
                                        sbCommittags.append("|");
                                    }
                                }
                            }
                            String tags="";
                            if(sbCommittags.length()!=0)
                            {
                                tags=sbCommittags.substring(0,sbCommittags.length()-1);
                            }
                            showLoading();
                            getTestApi().addToCard(2,SharePrefencesUtil.getCustomerCode(this),SharePrefencesUtil.getFID(this),
                                    solutionId,tags,sb).compose(this.<BaseBean>bindToLifecycle())
                                    .subscribeOn(Schedulers.io())
                                    .observeOn(AndroidSchedulers.mainThread())
                                    .subscribe(commitObserver);
                        }
                    }
                }
                break;
        }
    }
    Observer<BaseBean> commitObserver=new Observer<BaseBean>() {
        @Override
        public void onCompleted()
        {

        }

        @Override
        public void onError(Throwable e)
        {
            hideLoading();
            showToast(R.string.neterror);
        }

        @Override
        public void onNext(BaseBean baseBean)
        {
            hideLoading();
            Log.e("result",baseBean.getReturnInfo());
            showToast(baseBean.getReturnInfo());
            if(baseBean.getReturnNo().equals("1")){
                mHeadPopWindow.dismiss();
            }
        }
    };
    TextView tvPopModel,tvPopPrice,tvPopTag,tvPopNumAdd,tvPopNumDown,tvPopCommit;
    TextView tvPopNum;
    ImageView ivPopPic;
    ListView lvFits;
    LinearLayout llFlow;

    /**
     * 显示popwindow
     */
    private void showPopwindow()
    {
        View view = LayoutInflater.from(this).inflate(R.layout.pop_addshoppingcard_new, null);
        initPopView(view);
        setPopDatas();
        lvFits.setFocusable(false);
        ivDismissPop.setOnClickListener(this);
        mHeadPopWindow = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT, true);
        mHeadPopWindow.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        mHeadPopWindow.setAnimationStyle(android.R.style.Animation_Dialog);
        mHeadPopWindow.showAtLocation(tvAddShoppingcard, Gravity.TOP, 0, 0);
    }

    /**
     * 获取产品规格型号列表
     */
    ProductTagBean productTagBean;
    private void getProductQudaoParamList()
    {
        getTestApi().getProductQudaoParamList(productDetailBean.getContent().getFOutModel())
                .compose(this.<BaseBean>bindToLifecycle())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<BaseBean>()
                {
                    @Override
                    public void onCompleted()
                    {
                    }

                    @Override
                    public void onError(Throwable e)
                    {
                        hideLoading();
                        showToast(R.string.neterror);
                    }

                    @Override
                    public void onNext(BaseBean baseBean)
                    {
                        if(baseBean.getReturnNo().equals("1"))
                        {
                            String result=AESUtils.decode(baseBean.getContent());
                            result=start+result+end;
                            Log.e("result",result);
                            productTagBean=new Gson().fromJson(result,ProductTagBean.class);
                            if(productTagBean.getContent().size()==0)
                            {
                                tvPopTag.setVisibility(View.INVISIBLE);
                                llFlow.setVisibility(View.GONE);
                                llPopproductNum.setVisibility(View.VISIBLE);
                            }else{
                                llPopproductNum.setVisibility(View.GONE);
                                lvTags.setAdapter(new PopProductDetailTagsAdapter(NewProductDetailActivity.this));

                            }
                        }
                    }
                });
    }

    /**
     * 获取配件列表
     */
    private void getProductFittings()
    {
        getTestApi().getProductFittingList(productId)
                .compose(this.<BaseBean>bindToLifecycle())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(productFitsObserver);
    }

    Observer<BaseBean> productFitsObserver=new Observer<BaseBean>()
    {
        @Override
        public void onCompleted()
        {

        }

        @Override
        public void onError(Throwable e)
        {
            hideLoading();
            showToast(R.string.neterror);
        }

        @Override
        public void onNext(BaseBean baseBean)
        {
            if(baseBean.getReturnNo().equals("1"))
            {
                String result=AESUtils.decode(baseBean.getContent());
                result=start+result+end;
                Log.e("result",result);
                productFittingsBean=new Gson().fromJson(result,ProductFittingsBean.class);
                if(productFittingsBean.getContent().size()==0)
                {
                    llPopFits.setVisibility(View.GONE);
                }
                lvFits.setAdapter(new PopProductDetailFitsAdapter(NewProductDetailActivity.this));
            }else
            {
                baseBean.getReturnInfo();
            }
        }
    };

    /**
     * 设置popwindwow里的数据
     */
    private void setPopDatas()
    {
        tvPopModel.setText(productDetailBean.getContent().getFOutModel());
        tvPopPrice.setText(getResources().getString(R.string.money)+productDetailBean.getContent().getFStandPrice());
        tvPopTag.setText("已选");
        Glide.with(this)
                .load(productDetailBean.getContent().getFPicPath())
                .into(ivPopPic);
    }

    /**
     * 初始化popwindow里的数据
     * @param view
     */
    int totalCount;
    LinearLayout llPopFits;
    MyListView lvTags;
    LinearLayout llPopproductNum;
    private void initPopView(View view)
    {
        ivDismissPop= (ImageView) view.findViewById(R.id.iv_dismiss_pop);
        llPopproductNum=(LinearLayout)view.findViewById(R.id.ll_pop_productdetail_num);
        lvFits=(MyListView)view.findViewById(R.id.lv_pop_poductdetail_fits);
        lvTags=(MyListView)view.findViewById(R.id.lv_pop_poductdetail_tag);
        llPopFits=(LinearLayout)view.findViewById(R.id.ll_pop_poductdetail_fits);
        tvPopModel=(TextView)view.findViewById(R.id.tv_pop_productdetail_model);
        tvPopPrice=(TextView)view.findViewById(R.id.tv_pop_productdetail_price);
        tvPopTag=(TextView)view.findViewById(R.id.tv_pop_productdetail_tag);
        tvPopNumAdd=(TextView)view.findViewById(R.id.tv_pop_productdetail_add);
        tvPopNumDown=(TextView)view.findViewById(R.id.tv_pop_productdetail_down);
        tvPopNum=(TextView)view.findViewById(R.id.tv_pop_productdetail_num);
        tvPopNum.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                totalCount=Integer.parseInt(tvPopNum.getText().toString());
                View dialogView = LayoutInflater.from(NewProductDetailActivity.this).inflate(R.layout.dialog_edit_productnum, null);
                final Dialog dialog = new AlertDialog.Builder(NewProductDetailActivity.this)
                        .setView(dialogView).show();
                TextView tvadd = (TextView) dialog.findViewById(R.id.tv_editshop_add);
                TextView tvdown = (TextView) dialog.findViewById(R.id.tv_editshop_down);
                TextView tvdismiss = (TextView) dialog.findViewById(R.id.tv_editshop_dismiss);
                final TextView tvtrue = (TextView) dialog.findViewById(R.id.tv_editshop_true);
                final EditText etcount = (EditText) dialog.findViewById(R.id.et_editshop_count);
                KeyBoardUtils.openKeybord(etcount, NewProductDetailActivity.this);
                etcount.setText(totalCount + "");
                etcount.setSelection(etcount.getText().length());
                etcount.addTextChangedListener(new TextWatcher()
                {
                    @Override
                    public void beforeTextChanged(CharSequence s, int start, int count, int after)
                    {

                    }

                    @Override
                    public void onTextChanged(CharSequence s, int start, int before, int count)
                    {

                    }

                    @Override
                    public void afterTextChanged(Editable s)
                    {
                        if(!s.toString().equals(""))
                        {
                            totalCount=Integer.parseInt(s.toString());
                        }
                    }
                });
                tvadd.setOnClickListener(new View.OnClickListener()
                {
                    @Override
                    public void onClick(View v)
                    {
                        totalCount++;
                        etcount.setText(totalCount + "");
                        etcount.setSelection(etcount.getText().length());
                    }
                });
                tvdown.setOnClickListener(new View.OnClickListener()
                {
                    @Override
                    public void onClick(View v)
                    {
                        if (totalCount > 1)
                        {
                            totalCount--;
                            etcount.setText(totalCount + "");
                            etcount.setSelection(etcount.getText().length());
                        }
                    }
                });
                tvdismiss.setOnClickListener(new View.OnClickListener()
                {
                    @Override
                    public void onClick(View v)
                    {
                        KeyBoardUtils.closeKeybord(etcount,NewProductDetailActivity.this);
                        dialog.dismiss();
                    }
                });
                tvtrue.setOnClickListener(new View.OnClickListener()
                {
                    @Override
                    public void onClick(View v)
                    {
                        int count=0;
                        //循环计算所有已选配件的总数量
                        for(int i=0;i<fitTotalCount.size();i++)
                        {
                            if(fitChoose.get(i))
                            {
                                count+=fitTotalCount.get(i);
                            }
                        }
                        if("".equals(etcount.getText().toString()))
                        {
                            Toast.makeText(NewProductDetailActivity.this,R.string.notless,Toast.LENGTH_SHORT).show();
                            KeyBoardUtils.closeKeybord(etcount, NewProductDetailActivity.this);
                            dialog.dismiss();
                        }else if(0==Integer.parseInt(etcount.getText().toString())||count>Integer.parseInt(etcount.getText().toString()))
                        {
                            Toast.makeText(NewProductDetailActivity.this,R.string.notless,Toast.LENGTH_SHORT).show();
                            KeyBoardUtils.closeKeybord(etcount, NewProductDetailActivity.this);
                            dialog.dismiss();
                        }else if(100000<Integer.parseInt(etcount.getText().toString()))
                        {
                            Toast.makeText(NewProductDetailActivity.this,R.string.notmore,Toast.LENGTH_SHORT).show();
                            KeyBoardUtils.closeKeybord(etcount, NewProductDetailActivity.this);
                            dialog.dismiss();
                        }else if(!"".equals(etcount.getText().toString()))
                        {
                            totalCount=Integer.parseInt(etcount.getText().toString());
                            productTotalCount=totalCount;
                            tvPopNum.setText(totalCount+"");
                            KeyBoardUtils.closeKeybord(etcount, NewProductDetailActivity.this);
                            dialog.dismiss();
                        }
                    }
                });
            }
        });
        tvPopCommit=(TextView)view.findViewById(R.id.tv_pop_productdetail_commit);
        ivPopPic=(ImageView)view.findViewById(R.id.iv_pop_productdetail_pic);
        llFlow=(LinearLayout)view.findViewById(R.id.ll_pop_productdetail_tag);
        tvPopNumDown.setOnClickListener(this);
        tvPopNumAdd.setOnClickListener(this);
        tvPopCommit.setOnClickListener(this);
        getProductQudaoParamList();
        getProductFittings();
    }

    /**
     * 规格adapter
     */
    //记录每一个规格的数量，刚开始将每一个配件的数量设为0
    List<Integer> tagTotalCount;
    //记录每一个规格的选择状态（true为选中，false为未选中），刚开始将所有的状态置为false（未选中），选中后将状态置为true
    List<Boolean> tagChoose;
    TextView tvItemTagNumAdd,tvItemTagNumDown,tvItemTagNum;
    CheckBox cbItemTag;
    class PopProductDetailTagsAdapter extends BaseAdapter
    {
        Context context;
        public PopProductDetailTagsAdapter(Context context)
        {
            this.context=context;
            tagTotalCount=new ArrayList<>();
            tagChoose=new ArrayList<>();
            for (int i=0;i<productTagBean.getContent().size();i++)
            {
                if(i==0){
                    tagTotalCount.add(1);
                    tagChoose.add(true);
                }else{
                    tagTotalCount.add(0);
                    tagChoose.add(false);
                }
            }

        }
        @Override
        public int getCount() {
            return productTagBean.getContent().size();
        }

        @Override
        public Object getItem(int position) {
            return productTagBean.getContent().get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            convertView= LayoutInflater.from(context).inflate(R.layout.pop_productdetail_fits_item,null);
            tvItemTagNum=(TextView)convertView.findViewById(R.id.tv_pop_productdetail_item_num);
            tvItemTagNumAdd=(TextView)convertView.findViewById(R.id.tv_pop_productdetail_item_add);
            tvItemTagNumDown=(TextView)convertView.findViewById(R.id.tv_pop_productdetail_item_down);
            cbItemTag=(CheckBox)convertView.findViewById(R.id.cb_pop_productdetail_item_model);
            tvItemTagNumAdd.setOnClickListener(new TagNumSettingClick(position,tvItemTagNum,cbItemTag));
            tvItemTagNumDown.setOnClickListener(new TagNumSettingClick(position,tvItemTagNum,cbItemTag));
            cbItemTag.setOnClickListener(new TagNumSettingClick(position,tvItemTagNum,cbItemTag));
            tvItemTagNum.setOnClickListener(new TagNumSettingClick(position,tvItemTagNum,cbItemTag));
            cbItemTag.setText(productTagBean.getContent().get(position).getFQudaoParam());
            if(position==0){
                cbItemTag.setChecked(true);
                tvItemTagNum.setText("1");
            }
            return convertView;
        }

        class  TagNumSettingClick implements View.OnClickListener{
            int position;
            TextView tvTagnum;
            CheckBox cbTag;
            int tagTotalnum;
            public TagNumSettingClick(int position,TextView tvTagnum,CheckBox cbTag){
                this.position=position;
                this.tvTagnum=tvTagnum;
                this.cbTag=cbTag;
            }
            @Override
            public void onClick(View v) {
                switch (v.getId())
                {

                    case R.id.tv_pop_productdetail_item_num:
                        tagTotalnum=Integer.parseInt(tvTagnum.getText().toString());
                        View dialogView = LayoutInflater.from(NewProductDetailActivity.this).inflate(R.layout.dialog_edit_productnum, null);
                        final Dialog dialog = new AlertDialog.Builder(NewProductDetailActivity.this)
                                .setView(dialogView).show();
                        TextView tvadd = (TextView) dialog.findViewById(R.id.tv_editshop_add);
                        TextView tvdown = (TextView) dialog.findViewById(R.id.tv_editshop_down);
                        TextView tvdismiss = (TextView) dialog.findViewById(R.id.tv_editshop_dismiss);
                        final TextView tvtrue = (TextView) dialog.findViewById(R.id.tv_editshop_true);
                        final EditText etcount = (EditText) dialog.findViewById(R.id.et_editshop_count);
                        KeyBoardUtils.openKeybord(etcount, NewProductDetailActivity.this);
                        etcount.setText(tagTotalnum + "");
                        etcount.setSelection(etcount.getText().length());
                        etcount.addTextChangedListener(new TextWatcher()
                        {
                            @Override
                            public void beforeTextChanged(CharSequence s, int start, int count, int after)
                            {

                            }

                            @Override
                            public void onTextChanged(CharSequence s, int start, int before, int count)
                            {

                            }

                            @Override
                            public void afterTextChanged(Editable s)
                            {
                                if(!s.toString().equals(""))
                                {
                                    tagTotalnum=Integer.parseInt(s.toString());
                                }
                            }
                        });
                        tvadd.setOnClickListener(new View.OnClickListener()
                        {
                            @Override
                            public void onClick(View v)
                            {
                                tagTotalnum++;
                                etcount.setText(tagTotalnum + "");
                                etcount.setSelection(etcount.getText().length());
                            }
                        });
                        tvdown.setOnClickListener(new View.OnClickListener()
                        {
                            @Override
                            public void onClick(View v)
                            {
                                if (tagTotalnum > 0)
                                {
                                    tagTotalnum--;
                                    etcount.setText(tagTotalnum + "");
                                    etcount.setSelection(etcount.getText().length());
                                }else{
                                    showToast(R.string.notless);
                                }
                            }
                        });
                        tvdismiss.setOnClickListener(new View.OnClickListener()
                        {
                            @Override
                            public void onClick(View v)
                            {
                                KeyBoardUtils.closeKeybord(etcount,NewProductDetailActivity.this);
                                dialog.dismiss();
                            }
                        });
                        tvtrue.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                if("".equals(etcount.getText().toString()))
                                {
                                    Toast.makeText(NewProductDetailActivity.this,R.string.notless,Toast.LENGTH_SHORT).show();
                                    KeyBoardUtils.closeKeybord(etcount, NewProductDetailActivity.this);
                                    dialog.dismiss();
                                }
                                 else if(100000<Integer.parseInt(etcount.getText().toString()))
                                {
                                    Toast.makeText(NewProductDetailActivity.this, R.string.notmore,Toast.LENGTH_SHORT).show();
                                    KeyBoardUtils.closeKeybord(etcount, NewProductDetailActivity.this);
                                    dialog.dismiss();
                                }else if(!"".equals(etcount.getText().toString()))
                                {
                                    tagTotalnum=Integer.parseInt(etcount.getText().toString());
                                    if(tagTotalnum==0){
                                        cbTag.setChecked(false);
                                        tagChoose.set(position,false);
                                    }else{
                                        cbTag.setChecked(true);
                                        tagChoose.set(position,true);
                                    }
                                    tvTagnum.setText(tagTotalnum+"");
                                    tagTotalCount.set(position,tagTotalnum);
                                    KeyBoardUtils.closeKeybord(etcount, NewProductDetailActivity.this);
                                    dialog.dismiss();
                                }

                            }

                        });
                        break;
                    case R.id.tv_pop_productdetail_item_add:
                        cbTag.setChecked(true);
                        tagChoose.set(position,true);
                        tagTotalnum=tagTotalCount.get(position);
                        tagTotalnum++;
                        tvTagnum.setText(tagTotalnum+"");
                        tagTotalCount.set(position,tagTotalnum);
                        break;
                    case R.id.tv_pop_productdetail_item_down:
                        tagTotalnum=tagTotalCount.get(position);
                        if(tagTotalnum==0){
                            showToast(R.string.notless);
                        }else if(tagTotalnum==1){
                            cbTag.setChecked(false);
                            tagChoose.set(position, false);
                            tagTotalnum--;
                            tvTagnum.setText(tagTotalnum+"");
                            tagTotalCount.set(position,tagTotalnum);
                        }else{
                            tagTotalnum--;
                            tvTagnum.setText(tagTotalnum+"");
                            tagTotalCount.set(position,tagTotalnum);
                        }
                        break;
                    case R.id.cb_pop_productdetail_item_model:
                        boolean cb=!tagChoose.get(position);
                        tagChoose.set(position, cb);
                        cbTag.setChecked(cb);
                        break;
                }
            }
        }
    }


    /**
     * 产品配件Adapter
     */
    TextView tvItemNumAdd,tvItemNumDown,tvItemNum;
    CheckBox cbItemFit;
    //记录每一个配件的数量，刚开始将每一个配件的数量设为0
    List<Integer> fitTotalCount;
    //记录每一个配件的选择状态（true为选中，false为未选中），刚开始将所有的状态置为false（未选中），选中后将状态置为true
    List<Boolean> fitChoose;



    class PopProductDetailFitsAdapter extends BaseAdapter
    {
        Context context;
        public PopProductDetailFitsAdapter(Context context)
        {
            this.context=context;
            fitTotalCount=new ArrayList<>();
            fitChoose=new ArrayList<>();
            for (int i=0;i<productFittingsBean.getContent().size();i++)
            {
                fitTotalCount.add(0);
                fitChoose.add(false);
            }
        }
        @Override
        public int getCount()
        {
            return productFittingsBean.getContent().size();
        }

        @Override
        public Object getItem(int position)
        {
            return productFittingsBean.getContent().get(position);
        }

        @Override
        public long getItemId(int position)
        {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent)
        {
            convertView= LayoutInflater.from(context).inflate(R.layout.pop_productdetail_fits_item,null);
            tvItemNum=(TextView)convertView.findViewById(R.id.tv_pop_productdetail_item_num);
            tvItemNumAdd=(TextView)convertView.findViewById(R.id.tv_pop_productdetail_item_add);
            tvItemNumDown=(TextView)convertView.findViewById(R.id.tv_pop_productdetail_item_down);
            cbItemFit=(CheckBox)convertView.findViewById(R.id.cb_pop_productdetail_item_model);
            tvItemNumAdd.setOnClickListener(new MyPopNumClicklistener(position,tvItemNum,cbItemFit));
            tvItemNumDown.setOnClickListener(new MyPopNumClicklistener(position,tvItemNum,cbItemFit));
            cbItemFit.setOnClickListener(new MyPopNumClicklistener(position,tvItemNum,cbItemFit));
            cbItemFit.setText(productFittingsBean.getContent().get(position).getFOutModel());
            return convertView;
        }



    }

    /**
     * 配件的状态 以及数量选择时的点击事件
     */
    class MyPopNumClicklistener implements View.OnClickListener
    {
        int clickPosition;
        TextView tvClickNum;
        int totalnum;
        CheckBox cbClickItemFit;
        int count=0;
        public MyPopNumClicklistener(int clickPosition,TextView tvClickNum,CheckBox cbClickItemFit)
        {
            this.clickPosition=clickPosition;
            this.tvClickNum=tvClickNum;
            this.cbClickItemFit=cbClickItemFit;
        }
        @Override
        public void onClick(View v)
        {
            switch (v.getId())
            {
                case R.id.tv_pop_productdetail_item_add:
                    //添加
                    count=0;
                    if(cbClickItemFit.isChecked())
                    {//配件在选中情况下点击增加数量
                        //循环计算所有已选配件的总数量
                        for(int i=0;i<fitTotalCount.size();i++)
                        {
                            if(fitChoose.get(i))
                            {
                                count+=fitTotalCount.get(i);
                            }
                        }
                        //判断配件总数量是否大于产品数量
                        if(count>=Integer.parseInt(tvPopNum.getText().toString()))
                        {
                            showToast(R.string.notmore);
                        }else
                        {
                            fitChoose.set(clickPosition,true);
                            cbClickItemFit.setChecked(true);
                            totalnum=fitTotalCount.get(clickPosition);
                            totalnum++;
                            fitTotalCount.set(clickPosition,totalnum);
                            tvClickNum.setText(totalnum+"");
                        }
                    } else
                    {//配件在未选中情况下点击增加数量
                        //循环计算所有已选配件的总数量
                        for(int i=0;i<fitTotalCount.size();i++)
                        {
                            count+=fitTotalCount.get(i);
                        }
                        //判断配件总数量是否大于产品数量
                        if(count>=Integer.parseInt(tvPopNum.getText().toString()))
                        {
                            showToast(R.string.notmore);
                        }else
                        {
                            fitChoose.set(clickPosition,true);
                            cbClickItemFit.setChecked(true);
                            totalnum=fitTotalCount.get(clickPosition);
                            totalnum++;
                            fitTotalCount.set(clickPosition,totalnum);
                            tvClickNum.setText(totalnum+"");
                        }
                    }

                    break;
                case R.id.tv_pop_productdetail_item_down:
                    //减少
                    totalnum=fitTotalCount.get(clickPosition);
                    if(totalnum>0)
                    {
                        totalnum--;
                        fitTotalCount.set(clickPosition,totalnum);
                        tvClickNum.setText(totalnum+"");
                    }
                    else
                    {
                        showToast(R.string.notless);
                    }
                    if(totalnum==0)
                    {
                        fitTotalCount.set(clickPosition,0);
                        fitChoose.set(clickPosition,false);
                        cbClickItemFit.setChecked(false);
                    }
                    break;

                case R.id.cb_pop_productdetail_item_model:
                    //配件的选择（多选）
                    //添加
                    boolean cb=!fitChoose.get(clickPosition);
                    fitChoose.set(clickPosition, cb);
                    cbClickItemFit.setChecked(cb);
                    count=0;
                    //循环计算所有已选配件的总数量
                    for(int i=0;i<fitTotalCount.size();i++)
                    {
                        if (fitChoose.get(i))
                        {
                            count+=fitTotalCount.get(i);
                        }
                    }
                    //判断配件总数量是否大于产品数量
                    if(count>Integer.parseInt(tvPopNum.getText().toString()))
                    {
                        showToast(R.string.notmore);
                    }
                    Log.e("boolean",fitChoose.get(clickPosition)+"");
                    break;
            }
        }
    }
    /**
     * viewpagerAdapter
     */
    class Adapter extends FragmentPagerAdapter
    {
        private final Fragment[] fragments = new Fragment[2];
        private final String [] titles= {getResources().getString(R.string.productparam),getResources().getString(R.string.imgsize)};
        public Adapter(FragmentManager fm)
        {
            super(fm);
        }


        @Override
        public Fragment getItem(int position)
        {
            Fragment fragment = fragments[position];
            if (fragment == null)
            {
//                if(position==0)
//                {
//                    fragment = new ProductMemoFragment(productDetailBean.getContent().getFMemo());
//                    fragments[position] = fragment;
//                }else
                if (position==0)
                {
                    if(productParamBean.getContent()!=null)
                    {

                        fragment = new ProductParamFragment(productParamBean.getContent().getFParam());
                    }else
                    {
                        fragment = new ProductParamFragment("");
                    }
                    fragments[position] = fragment;
                }else if (position==1)
                {
                    if(productParamBean.getContent()!=null)
                    {
                        fragment = new ProductSizePicFragment(productParamBean.getContent().getFSizePicPath());
                    }else
                    {
                        fragment = new ProductParamFragment("");
                    }
                    fragments[position] = fragment;
                }
            }
            return fragment;
        }

        @Override
        public int getCount()
        {
            return 2;
        }

        @Override
        public CharSequence getPageTitle(int position)
        {

            return titles[position];
        }
    }
}
